<template>
	<div id="main">
		<div class="container">
			<div class="content">
				<div class="problem-detail">
					<el-button type="" @click="tolist">题目列表</el-button>

					<h1 id="title">{{ title }}</h1>

					<!-- 添加全屏浏览和切换布局的功能 -->
					<div class="pc-text-raw text-xs ellipsis"
						style="text-align: center; padding: 5px; margin: 2px; font-size: 12px; border: 1px solid #ccc; display: inline-block;"
						@click="toggleFullScreen">
						全屏浏览
					</div>
					<div class="pc-text-raw text-xs ellipsis"
						style="text-align: center; padding: 5px; margin: 2px; font-size: 12px; border: 1px solid #ccc; display: inline-block;"
						@click="toggleLayout">
						切换布局
					</div>

					<div class="line" style="text-align: center"></div>

					<div class="description">
						<h2>描述:</h2>
						<markdown-it-vue class="md-body" :content="description" :options="options" />
					</div>
					<div class="input-output">
						<h2>输入格式</h2>
						<markdown-it-vue class="md-body" :content="inputFormat" :options="options" />
						<h2>输出格式</h2>
						<markdown-it-vue class="md-body" :content="outputFormat" :options="options" />
					</div>

					<div class="example">
						<h2>示例</h2>
						<div>
							<h3>输入:</h3>
							<pre class="pre_Z0SZq">
      <code>{{ inputExample }}</code>
    </pre>
							<h3>输出:</h3>
							<pre class="pre_Z0SZq">
      <code>{{ outputExample }}</code>
    </pre>
						</div>
					</div>

				</div>
				<div class="separator" @mousedown="startDrag"></div>
				<div class="compiler">
					<div class="editor-container">
						<div class="editor-controls">
							<div class="dropdown-container">
								<div class="el-input el-input--suffix is-borderless">
									<input type="text" readonly="readonly" autocomplete="off" placeholder="请选择"
										class="el-input__inner" @click="toggleDropdown" :value="modeLabel" />
									<span class="el-input__suffix" @click="toggleDropdown">
										<span class="el-input__suffix-inner">
											<i
												:class="['el-select__caret', 'el-input__icon', dropdownVisible ? 'el-icon-arrow-down' : 'el-icon-arrow-up']"></i>
										</span>
									</span>
								</div>
								<div v-if="dropdownVisible" class="language-dropdown">
									<ul>
										<li v-for="lang in languages" :key="lang.value" @click="selectLanguage(lang)">
											{{ lang.label }}
										</li>
									</ul>
								</div>
							</div>
							<button @click="submitCode" :disabled="isSubmitting" class="submit-btn">
								<img v-if="isSubmitting"
									src="https://static.leetcode.cn/cn-frontendx-assets/production/_next/static/images/light-judging-9d7b0f1c4035b59af3a7d6ccd8e0ac12.gif"
									alt="判题中..." class="h-5 w-5">
								<span v-else>提交代码</span>
							</button>
						</div>
						<AceEditor v-model="code" :mode="selectedLanguage" theme="github" />
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import axios from 'axios';
	import AceEditor from './AceEditor.vue'; // 导入 AceEditor 组件
	import MarkdownItVue from 'markdown-it-vue'
	import {
		config
	} from '../utils/constant.js'
	import eventBus from '../utils/eventBus.js'
	export default {
		name: 'ProblemDetail',
		components: {
			AceEditor,
			MarkdownItVue
		},
		data() {
			return {
				// 模拟题目数据
				title: '测试题目 1',
				description: '这是一个测试题目，用于检查页面功能。请编写一个程序来输出输入整数的平方。',
				inputFormat: '输入格式：一行整数 n',
				outputFormat: '输出格式：一行整数 n 的平方',
				inputExample: '输入示例：\\n5',
				outputExample: '输出示例：\\n25',
				prevProblemId: '123',
				nextProblemId: '456',
				code: '// 请在这里编写代码\\nconsole.log("Hello, World!");',
				// 其他组件数据
				isDragging: false,
				leftWidth: '50%',
				isSubmitting: false,
				dropdownVisible: false,
				languages: [{
						label: 'JavaScript',
						value: 'javascript'
					},
					{
						label: 'Python',
						value: 'python'
					},
					{
						label: 'Java',
						value: 'java'
					},
					{
						label: 'C/C++',
						value: 'c_cpp'
					},
					{
						label: 'HTML',
						value: 'html'
					},
					{
						label: 'CSS',
						value: 'css'
					},
					{
						label: 'Ruby',
						value: 'ruby'
					},
					{
						label: 'Go',
						value: 'go'
					},
				],
				selectedLanguage: 'C/C++',
				modeLabel: 'C++',
				options: {}
			};
		},
		computed: {
			// description_com() {
			// 	return this.markdownRender.render(this.description)
			// },
			// inputFormat_com() {
			// 	this.renderMdText(this.inputFormat);
			// },
			// outputFormat_com() {
			// 	this.renderMdText(this.outputFormat);
			// },
		},
		created() {
			console.log(this.$route.params.id)
			let p_id = this.$route.params.id
			let firstCharLower = p_id.charAt(0).toLowerCase() + p_id.slice(1);
			console.log(firstCharLower)
			const axiosconfig = {
				method: 'post',
				url: config.baseUrl + '/problem/' + firstCharLower + '/',

			};
			axios(axiosconfig)
				.then(function (response) {
					console.log(response);
				})
				.catch(function (error) {
					console.log(error);
				});
			// this.$router.push('/commit')
		},
		mounted() {
			this.fetchProblemData(this.$route.params.id);
			document.addEventListener('mouseup', this.stopDrag);
			document.addEventListener('mousemove', this.onDrag);
		},
		beforeDestroy() {
			document.removeEventListener('mouseup', this.stopDrag);
			document.removeEventListener('mousemove', this.onDrag);
		},
		methods: {
			tolist(){
				this.$router.push("/dashboard")
			},
			async fetchProblemData(id) {
				try {
					const response = await axios.get(config.baseUrl + `/problem/${id}/`);
					console.log(response.data);

					this.title = response.data.question;
					this.description = response.data.description_question;
					this.inputFormat = response.data.description_input;
					this.outputFormat = response.data.description_output;
					this.inputExample = response.data.expinput;
					this.outputExample = response.data.expoutput;

					this.prevProblemId = response.data.prevProblemId;
					this.nextProblemId = response.data.nextProblemId;
				} catch (error) {
					console.error('获取题目数据失败:', error);
				}
			},
			renderMdText(text) {
				//生成html
				return this.markdownRender.render(text)
			},


			goToPrevProblem() {
				if (this.prevProblemId) {
					this.$router.push({
						name: 'ProblemDetail',
						params: {
							id: this.prevProblemId
						}
					});
				}
			},
			goToNextProblem() {
				if (this.nextProblemId) {
					this.$router.push({
						name: 'ProblemDetail',
						params: {
							id: this.nextProblemId
						}
					});
				}
			},
			startDrag(event) {
				this.isDragging = true;
				event.preventDefault();
			},
			stopDrag() {
				this.isDragging = false;
			},
			onDrag(event) {
				// if (!this.isDragging) return;
				// const container = this.$el.querySelector('.content');
				// const newWidth = event.clientX - container.getBoundingClientRect().left;
				// const percentage = (newWidth / container.offsetWidth) * 100;
				// this.leftWidth = `${percentage}%`;
				// this.$nextTick(() => {
				// 	const problemDetail = this.$el.querySelector('.problem-detail');
				// 	problemDetail.style.width = this.leftWidth;
				// });
			},
			async submitCode() {
				if (this.isSubmitting) return; // 如果正在提交，则不执行任何操作
				//加载栏
				const loading = this.$loading();
				setTimeout(() => {
					loading.close();
				}, 1000);
				// this.isSubmitting = true; // 设置提交状态为正在提交
				const cookie_accese = this.getCookie("access_token")
				console.log(cookie_accese + "this is cookie_accese")
				let FormData = require('form-data');
				let data = new FormData();

				data.append('problem_id', this.$route.params.id);
				data.append('code', this.code);

				const cookie_header = "Bearer " + cookie_accese
				const axiosconfig = {
					method: 'post',
					url: config.baseUrl + '/judge/judge/',
					headers: {
						'Authorization': `${cookie_header}`
					},
					data: data
				};
				let _self = this
				console.log(config)
				axios(axiosconfig)
					.then(function (response) {
						console.log(response);
						// eventBus.$emit("submit_response", response.data.judge)
						sessionStorage.setItem('response', JSON.stringify(response));
						setTimeout(() => {
							_self.$router.push({
  path: '/commit',
  query: { id: _self.$route.params.id }
});
						}, 1000)

					})
					.catch(function (error) {
						// console.log(error);
					});

				// eventBus.$emit("submit_response", response.data)

			},
			getCookie(cookieName) {
				const strCookie = document.cookie
				const cookieList = strCookie.split(';')

				for (let i = 0; i < cookieList.length; i++) {
					const arr = cookieList[i].split('=')
					if (cookieName === arr[0].trim()) {
						return arr[1]
					}
				}

				return ''
			},

			toggleDropdown() {
				this.dropdownVisible = !this.dropdownVisible;
			},
			selectLanguage(lang) {
				this.selectedLanguage = lang.value; // 更新选择的语言
				this.modeLabel = lang.label; // 更新显示的语言标签
				this.dropdownVisible = false; // 关闭下拉框
			},

			toggleFullScreen() {
				if (!document.fullscreenElement) {
					document.documentElement.requestFullscreen();
				} else {
					if (document.exitFullscreen) {
						document.exitFullscreen();
					}
				}
			},

			toggleLayout() {
				const problemDetail = this.$el.querySelector('.problem-detail');
				const compiler = this.$el.querySelector('.compiler');
				const content = this.$el.querySelector('.content');

				if (content.style.flexDirection === 'row' || !content.style.flexDirection) {
					// 当前布局为横向分布，切换为纵向分布
					content.style.flexDirection = 'column';
					problemDetail.style.width = '100%';
					compiler.style.width = '100%';
				} else {
					// 当前布局为纵向分布，切换为横向分布
					content.style.flexDirection = 'row';
					problemDetail.style.width = '50%';
					compiler.style.width = '50%';
				}
			}
		}
	};
</script>

<style scoped>
	#main {
		background: linear-gradient(to bottom right, #e0f7fa, #b3e5fc);
		/* 以下属性可以使背景覆盖整个页面 */
		height: 100vh;
		margin: 0;
		padding: 0;
	}

	.container {
		max-height: 5000px;
		max-width: 5000px;
		height: 100vh;
		display: flex;
		flex-direction: column;
		/* 允许子元素垂直排列 */
		padding: 1px;
		/* margin: 20px */
	}

	.content {
		display: flex;
		/* 水平布局 */
		flex-direction: row;
		/* 明确设置为横向布局 */
		flex: 1;
		margin: 20px 20px 20px 20px;
		border-radius: 10px;
	}

	.problem-detail {
		flex: 0 0 auto;
		/* 不允许自适应，使用固定宽度 */
		border: 3px solid #f2f4f2;
		padding: 1px;
		background-color: white;
		width: 50%;
		/* 默认宽度 */
	}

	.separator {
		width: 10px;
		/* 分隔条的宽度 */
		cursor: ew-resize;
		/* 鼠标样式 */
		background-color: #ccc;
		/* 分隔条的背景颜色 */
	}

	.compiler {
		flex: 1;
		/* 占据剩余空间 */
		border: 3px solid #f2f4f2;
		padding: 1px;
		background-color: white;
		/* height: 100%; */
		/* 如果设置了高度，请注释掉或设置为100% */
	}

	.editor-container {
		display: flex;
		flex-direction: column;
		/* 使编辑器和按钮垂直排列 */
		width: 100%;
		/* 使编辑器容器宽度为100% */
		height: 100%;
		/* 使编辑器容器高度为100% */
		min-height: 100%;
		/* 确保编辑器容器至少与父容器一样高 */
	}


	.ta-nav-container {
		display: flex;
		/* 使用flex布局 */
		justify-content: center;
		/* 水平居中对齐 */
		width: 97.4%;
		/* 使容器宽度为100% */
		margin: 15px 20px 0px 20px;
	}

	.nav-left {
		display: flex;
		/* 使用flex布局 */
		justify-content: flex-end;
		/* 水平居中对齐 */
		flex-basis: auto;
		/* 允许自适应宽度 */
	}

	.editor-controls {
		display: flex;
		/* 使用flex布局 */
		justify-content: space-between;
		/* 水平分散对齐 */
		align-items: center;
		/* 垂直居中对齐 */
		margin-bottom: 10px;
		/* 控制按钮与编辑器的间距 */
		flex: 0 0 auto;
		/* 不允许自适应，使用固定宽度 */
		width: 100%;
		/* 使按钮宽度与语言选择器按钮宽度一致 */
	}

	.dropdown-container {
		display: flex;
		align-items: center;
	}

	.el-input {
		width: 150px;
		/* 设置选择框的宽度 */
		border: 1px solid hsl(224, 12%, 76%);
		/* 设置边框颜色 */
		border-radius: 5px;
		/* 设置边框圆角 */
	}

	.el-input__inner {
		height: 30px;
		/* 设置选择框的高度 */
		padding: 8px;
		/* 设置内边距 */
		font-size: 14px;
		/* 设置字体大小 */
		background-color: #f9f9f9;
		/* 设置背景颜色 */
		color: #333;
		/* 设置字体颜色 */
	}

	.el-select__caret {
		color: #999;
		/* 设置箭头颜色 */
		font-size: 16px;
		/* 设置箭头大小 */
	}

	.el-icon-arrow-up {
		transform: rotate(180deg);
		/* 旋转箭头 */
	}

	.submit-btn {
		padding: 8px 12px;
		background-color: #aeebe6;
		border: 1px solid #fafafa;
		border-radius: 5px;
		cursor: pointer;
	}

	.submit-btn:disabled {
		cursor: not-allowed;
		opacity: 0.5;
	}

	.submit-btn img {
		width: 20px;
		/* 设置加载图标的大小 */
		height: 20px;
		/* 设置加载图标的大小 */
	}

	.language-dropdown {
		position: absolute;
		/* 设置下拉框为绝对定位 */
		background: white;
		/* 设置下拉框的背景颜色为白色 */
		border: 1px solid #dcdfe6;
		/* 设置下拉框的边框 */
		z-index: 10;
		/* 设置下拉框的堆叠顺序 */
		width: 20%;
		/* 设置下拉框的宽度 */
		top: 30px;
		/* 设置下拉框的顶部位置 */
		left: 0;
		/* 设置左侧位置 */
		right: 0;
		/* 设置右侧位置 */
		margin: auto;
		/*居中对齐 */
	}

	.language-dropdown ul {
		list-style: none;
		/* 去掉无序列表的默认样式 */
		padding: 0;
		/* 去掉列表的内边距 */
		margin: 0;
		/* 去掉列表的外边距 */
	}

	.language-dropdown li {
		padding: 8px 12px;
		/* 设置列表项的内边距 */
		cursor: pointer;
		/* 鼠标悬停时显示为手形 */
	}

	.language-dropdown li:hover {
		background: hsl(216, 33%, 97%);
		/* 鼠标悬停时改变背景颜色 */
	}

	.pc-text-raw {
		cursor: pointer;
		/* 鼠标悬停时显示为手形 */
		user-select: none;
		/* 禁止文本选择 */
		margin: 1px 0;
		/* 上下间距 */
		padding: 0px 10px;
		/* 内边距 */
		background-color: #f0f0f0;
		/* 背景颜色 */
		border-radius: 5px;
		/* 圆角 */
		transition: background-color 0.3s;
		/* 背景颜色过渡效果 */

	}

	.pc-text-raw:hover {
		background-color: #e0e0e0;
		/* 鼠标悬停时的背景颜色 */
	}

	.line {
		width: 100%;
		height: 1px;
		background-color: rgb(216, 216, 216);
		margin-top: 10px;
	}

	.pre_Z0SZq {
		border: 1px solid #ccc;
		/* 边框颜色 */
		padding: 10px;
		/* 内边距 */
		background-color: #f9f9f9;
		/* 背景颜色 */
		border-radius: 5px;
		/* 圆角 */
		overflow: auto;
		/* 处理溢出内容 */
	}

	.language-in {
		font-family: monospace;
		/* 使用等宽字体 */
	}
</style>